package controllers

import (
	"admin-glm-go/internal/models"
	"admin-glm-go/internal/response"
	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
	_ "time"
)

// MemberListRequest 会员列表请求参数
// @Description 会员列表请求参数
// @Accept json
// @Produce json
// @Param page query int false "页码"
// @Param pageSize query int false "每页数量"
// @Param level query int false "会员等级"
// @Param status query int false "状态"
// @Param nickname query string false "昵称"
// @Param phone query string false "手机号"
// @Param email query string false "邮箱"
type MemberListRequest struct {
	Page     int    `form:"page"`
	PageSize int    `form:"pageSize"`
	LevelID  int    `form:"level"`
	Status   int    `form:"status"`
	Nickname string `form:"nickname"`
	Phone    string `form:"phone"`
	Email    string `form:"email"`
}

// AddMemberRequest 添加会员请求参数
// @Description 添加会员请求参数
// @Accept json
// @Produce json
// @Param body body AddMemberRequest true "会员信息"
type AddMemberRequest struct {
	Username string `json:"username" binding:"required"`
	Password string `json:"password" binding:"required"`
	Nickname string `json:"nickname"`
	Avatar   string `json:"avatar"`
	Email    string `json:"email"`
	Phone    string `json:"phone"`
	Gender   int    `json:"gender"`
	Birthday string `json:"birthday"`
	LevelID  uint64 `json:"levelId"`
	Status   int    `json:"status"`
}

// UpdateMemberRequest 更新会员请求参数
// @Description 更新会员请求参数
// @Accept json
// @Produce json
// @Param body body UpdateMemberRequest true "会员信息"
type UpdateMemberRequest struct {
	ID       uint64 `json:"id" binding:"required"`
	Username string `json:"username" binding:"required"`
	Nickname string `json:"nickname"`
	Avatar   string `json:"avatar"`
	Email    string `json:"email"`
	Phone    string `json:"phone"`
	Gender   int    `json:"gender"`
	Birthday string `json:"birthday"`
	LevelID  uint64 `json:"levelId"`
	Status   int    `json:"status"`
}

// ResetMemberPasswordRequest 重置会员密码请求参数
// @Description 重置会员密码请求参数
// @Accept json
// @Produce json
// @Param body body ResetMemberPasswordRequest true "重置密码参数"
type ResetMemberPasswordRequest struct {
	ID       uint64 `json:"id" binding:"required"`
	Password string `json:"password" binding:"required"`
}

// MemberController 会员控制器
// @Description 会员管理控制器，处理会员相关的CRUD操作
// @Tags 会员管理模块
type MemberController struct {
	db *gorm.DB
}

// NewMemberController 创建会员控制器
// @Description 创建会员控制器实例
// @Param db *gorm.DB 数据库连接实例
// @Return *MemberController 会员控制器实例
func NewMemberController(db *gorm.DB) *MemberController {
	return &MemberController{db: db}
}

// GetMemberList 获取会员列表
// @Summary 获取会员列表
// @Description 获取会员列表
// @Tags 会员管理模块
// @Accept json
// @Produce json
// @Security ApiKeyAuth
// @Param page query int false "页码"
// @Param pageSize query int false "每页数量"
// @Param level query int false "会员等级"
// @Param status query int false "状态"
// @Param nickname query string false "昵称"
// @Param phone query string false "手机号"
// @Param email query string false "邮箱"
// @Success 200 {object} response.Response
// @Router /member/list [get]
func (ctrl *MemberController) GetMemberList(c *gin.Context) {
	var req MemberListRequest
	if err := c.ShouldBindQuery(&req); err != nil {
		response.ParamError(c)
		return
	}

	// 设置默认值
	if req.Page <= 0 {
		req.Page = 1
	}
	if req.PageSize <= 0 {
		req.PageSize = 10
	}

	// 构建查询条件
	query := ctrl.db.Model(&models.Member{}).Preload("Level")
	if req.LevelID > 0 {
		query = query.Where("level_id = ?", req.LevelID)
	}
	if req.Status != 0 {
		query = query.Where("status = ?", req.Status)
	}
	if req.Nickname != "" {
		query = query.Where("nickname LIKE ?", "%"+req.Nickname+"%")
	}
	if req.Phone != "" {
		query = query.Where("phone LIKE ?", "%"+req.Phone+"%")
	}
	if req.Email != "" {
		query = query.Where("email LIKE ?", "%"+req.Email+"%")
	}

	// 获取总数
	var total int64
	query.Count(&total)

	// 分页查询
	var members []models.Member
	offset := (req.Page - 1) * req.PageSize
	err := query.Offset(offset).Limit(req.PageSize).Order("id DESC").Find(&members).Error
	if err != nil {
		response.ServerError(c)
		return
	}

	// 构建响应数据
	var records []gin.H
	for _, member := range members {
		levelName := ""
		if member.LevelID != nil {
			levelName = member.Level.Name
		}

		lastLoginTime := ""
		if member.LastLoginTime != nil {
			lastLoginTime = member.LastLoginTime.Format("2006-01-02 15:04:05")
		}

		birthday := ""
		if member.Birthday != nil {
			birthday = member.Birthday.Format("2006-01-02")
		}

		record := gin.H{
			"id":           member.ID,
			"username":     member.Username,
			"nickname":     member.Nickname,
			"avatar":       member.Avatar,
			"email":        member.Email,
			"phone":        member.Phone,
			"gender":       member.Gender,
			"birthday":     birthday,
			"levelId":      member.LevelID,
			"levelName":    levelName,
			"points":       member.Points,
			"balance":      member.Balance,
			"status":       member.Status,
			"lastLoginTime": lastLoginTime,
			"lastLoginIp":  member.LastLoginIP,
			"createTime":   member.CreateTime.Format("2006-01-02 15:04:05"),
			"updateTime":   member.UpdateTime.Format("2006-01-02 15:04:05"),
		}
		records = append(records, record)
	}

	response.PageSuccess(c, total, records, req.Page, req.PageSize)
}

// GetMemberDetail 获取会员详情
// @Summary 获取会员详情
// @Description 获取会员详情
// @Tags 会员管理模块
// @Accept json
// @Produce json
// @Security ApiKeyAuth
// @Param id path int true "会员ID"
// @Success 200 {object} response.Response
// @Router /member/detail/{id} [get]
func (ctrl *MemberController) GetMemberDetail(c *gin.Context) {
	id := c.Param("id")

	// 查询会员
	var member models.Member
	if err := ctrl.db.Preload("Level").First(&member, id).Error; err != nil {
		response.NotFound(c)
		return
	}

	// 构建响应数据
	levelName := ""
	if member.LevelID != nil {
		levelName = member.Level.Name
	}

	lastLoginTime := ""
	if member.LastLoginTime != nil {
		lastLoginTime = member.LastLoginTime.Format("2006-01-02 15:04:05")
	}

	birthday := ""
	if member.Birthday != nil {
		birthday = member.Birthday.Format("2006-01-02")
	}

	detail := gin.H{
		"id":           member.ID,
		"username":     member.Username,
		"nickname":     member.Nickname,
		"avatar":       member.Avatar,
		"email":        member.Email,
		"phone":        member.Phone,
		"gender":       member.Gender,
		"birthday":     birthday,
		"levelId":      member.LevelID,
		"levelName":    levelName,
		"points":       member.Points,
		"balance":      member.Balance,
		"status":       member.Status,
		"lastLoginTime": lastLoginTime,
		"lastLoginIp":  member.LastLoginIP,
		"createTime":   member.CreateTime.Format("2006-01-02 15:04:05"),
		"updateTime":   member.UpdateTime.Format("2006-01-02 15:04:05"),
	}

	response.Success(c, detail)
}